import 'package:app_30/home/register_page.dart';
import 'package:app_30/models/load_entity.dart';
import 'package:app_30/net/dio_utils.dart';
import 'package:app_30/net/http_api.dart';
import 'package:app_30/res/constant.dart';
import 'package:app_30/res/gaps.dart';
import 'package:app_30/util/change_notifier_manage.dart';
import 'package:app_30/util/other_utils.dart';
import 'package:app_30/util/sp_util.dart';
import 'package:app_30/widgets/load_image.dart';
import 'package:app_30/widgets/my_button.dart';
import 'package:app_30/widgets/my_scroll_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'main_page.dart';
import 'my_text_field.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage>
    with ChangeNotifierMixin<LoginPage> {
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  bool _clickable = false;

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _nameController: callbacks,
      _passwordController: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      /// 显示状态栏和导航栏
      SystemChrome.setEnabledSystemUIOverlays(
          [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    });
    _nameController.text = SpUtil.getString(Constant.phone).nullSafe;
  }

  void _verify() {
    final String name = _nameController.text;
    final String password = _passwordController.text;
    bool clickable = true;
    if (name.isEmpty || name.length < 4) {
      clickable = false;
    }
    if (password.isEmpty || password.length < 4) {
      clickable = false;
    }

    /// 状态不一样再刷新，避免不必要的setState
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MyScrollView(
        keyboardConfig: Utils.getKeyboardActionsConfig(
            context, <FocusNode>[_nodeText1, _nodeText2]),
        children: _buildBody,
      ),
    );
  }

  List<Widget> get _buildBody => <Widget>[
        Stack(
          // alignment: Alignment.bottomCenter,
          alignment: AlignmentDirectional(0.0, 1.5),
          children: const <Widget>[
            LoadAssetImage(
              'bg',
              fit: BoxFit.fitWidth,
            ),
            Align(
              child: LoadAssetImage(
                'logo',
                width: 70,
                height: 70,
              ),
            ),
          ],
        ),
        Gaps.vGap50,
        Padding(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 20.0),
          child: MyTextField(
            key: const Key('phone'),
            focusNode: _nodeText1,
            controller: _nameController,
            maxLength: 20,
            keyboardType: TextInputType.text,
            hintText: '请输入账号',
          ),
        ),
        Gaps.vGap8,
        Padding(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0),
          child: MyTextField(
            key: const Key('password'),
            keyName: 'password',
            focusNode: _nodeText2,
            isInputPwd: true,
            controller: _passwordController,
            keyboardType: TextInputType.visiblePassword,
            maxLength: 20,
            hintText: '请输入密码',
          ),
        ),
        Gaps.vGap24,
        Padding(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0),
          child: MyButton(
            key: const Key('login'),
            onPressed: _clickable ? _gotoHome : null,
            text: '登录',
          ),
        ),
        Gaps.vGap16,
        Container(
            alignment: Alignment.center,
            child: GestureDetector(
              child: Text(
                '还没账号？快去注册',
                key: const Key('noAccountRegister'),
                style: TextStyle(color: Theme.of(context).primaryColor),
              ),
              onTap: () => gotoRegister(),
            ))
      ];

  void gotoRegister() {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) {
        return RegisterPage();
      },
    ));
  }

  void _gotoHome() {
    Navigator.of(context).pop();
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) {
        return MyMainPage();
      }),
    );
  }

  login() async {
    Map<String, dynamic> map = Map();
    map['user'] = "will111";
    map['password'] = 'will222';

    await DioUtils.instance.requestNetwork<LoadEntity>(
      Method.post,
      HttpApi.denglu,
      params: map,
      onSuccess: (data) {
        print('${data!.user}');
      },
      onError: (_, __) {
        print('$_, $__');
      },
    );
  }
}
